// src/stores/homepage.ts
import {defineStore} from 'pinia';
import {HomepageChartData} from '@/api/types/homepage';
import {getConfigYear} from '@/api/services/config-calc-year';
import {getVepShowcaseData} from "api/services/vepService";
import {getGepShowcaseData} from "api/services/gepService";

// 定义乡镇数据接口
interface TownItem {
  culture: string;
  material: string;
  name: string;
  regulation: string;
  has_data?: boolean; // 部分数据包含此字段
}

// 定义 gepResultsItem 接口
interface gepResultsItem {
  data_towns: number;
  district: {
    culture: string;
    material: string;
    name: string;
    regulation: string;
  };
  missing_count: number;
  missing_towns: any[]; // 根据示例数据为空数组
  total_towns: number;
  towns: TownItem[];
}

interface HomepageState {
  chartData: HomepageChartData | null;
  isDataLoaded: boolean;
  year: number;
  district: string;
  gepResults:gepResultsItem | null;
  vepResults:any[];
  gepValue: number;
}

export const useHomepageStore = defineStore('homepage', {
  state: (): HomepageState => ({
    chartData: null,
    isDataLoaded: false,
    year: new Date().getFullYear() - 1, // 默认值
    district: '铅山县',
    gepResults: null,
    vepResults:[],
    gepValue: 0,
  }),

  actions: {
    async initializeYear() {
      try {
        const {data} = await getConfigYear('yanshan_year');
        if (data && data.exists && data.value) {
          this.year = Number(data.value)
          console.log('加载配置的年份',data.value)
        }else{
          console.log('Not exist year config:', data);
          // 保持默认年份
        }

      } catch (error) {
        console.error('Failed to fetch year config:', error);
        // 保持默认年份
      }
    },

    async fetchVepResults() {
      try {
        const response = await getVepShowcaseData()
        // 处理数据，将数值保留两位小数
        console.log('vep - response',response)

        this.vepResults = (response.data.selected_projects || []).map((item: any) => {
          const processedItem = {...item};

          // 遍历对象的所有属性
          Object.keys(processedItem).forEach(key => {
            // 检查属性值是否为数字且不是整数
            if (typeof processedItem[key] === 'number' && !Number.isInteger(processedItem[key])) {
              // 保留两位小数
              processedItem[key] = Number(processedItem[key].toFixed(2));
            }
          });

          return processedItem;
        });
      } catch (error) {
        console.error('获取VEP结果失败:', error)
        ElMessage.error('获取VEP结果失败')
      }
    },

    async fetchGepResults ()  {
      if (!this.year) {
        ElMessage.warning('请先配置年份')
        return
      }

      try {
        const response = await getGepShowcaseData(this.year)
        this.gepResults = response.data.showcase_data || {
          district: {},
          towns: [],
          total_towns: 0,
          data_towns: 0,
          missing_count: 0,
          missing_towns: []
        }

        // 修复：增加可选链和默认值处理
        const material = Number(this.gepResults?.district?.material) || 0;
        const culture = Number(this.gepResults?.district?.culture) || 0;
        const regulation = Number(this.gepResults?.district?.regulation) || 0;
        this.gepValue = material + culture + regulation;

        // ElMessage.success('数据查询成功')
      } catch (error) {
        console.error('获取GEP数据失败:', error)
        ElMessage.error('GepResults获取数据失败')
      }
    },

    setChartData(data: HomepageChartData) {
      this.chartData = data;
      this.isDataLoaded = true;
    },

    setDataLoading(loading: boolean) {
      this.isDataLoaded = !loading;
    },

    setYear(year: number) {
      this.year = year;
    },

    // setDistrict(district: string) {
    //   this.district = district;
    // },
    //
    // clearData() {
    //   this.chartData = null;
    //   this.isDataLoaded = false;
    // }
  },

  getters: {
    getChartData: (state) => state.chartData,
    getIsDataLoaded: (state) => state.isDataLoaded,
    getYear: (state) => state.year,
    getDistrict: (state) => state.district,

    // 添加 ecologicalValue 计算属性
    ecologicalValue: (state) => {
      const pieData = state.chartData?.pie01;
      if (!pieData || pieData.length < 3) return '0.00';
      const total = pieData.reduce((sum, item) => sum + item.value, 0);
      return (total / 10000).toFixed(2); // 保留两位小数
    }
  }
});
